package com.iweipan.activity;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.iweipan.R;
import com.iweipan.base.WPBaseActivity;
import com.iweipan.base.WPUrlBase;
import com.iweipan.utils.snackbar.SnackbarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.security.MessageDigest;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

import static com.iweipan.R.id.money_ed;
import static com.iweipan.R.id.one_bai;
import static com.iweipan.base.WPUrlBase.WP_USER_BALANCES;
import static com.iweipan.base.WPUrlBase.WP_USER_CUSTOMER;

/**
 * Created by Administrator on 2016/11/29.
 */

public class MoneyActivity extends WPBaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.lay_out)
    LinearLayout layOut;
    @BindView(R.id.wx_pay)
    TextView wxPay;
    @BindView(R.id.zfb_pay)
    TextView zfbPay;
    @BindView(R.id.ten)
    TextView ten;
    @BindView(R.id.fifty)
    TextView fifty;
    @BindView(one_bai)
    TextView oneBai;
    @BindView(R.id.wubai)
    TextView wubai;
    @BindView(R.id.other)
    TextView other;
    @BindView(R.id.my_money)
    TextView myMoney;
    @BindView(money_ed)
    EditText moneyEd;
    @BindView(R.id.pay)
    Button pay;
    @BindView(R.id.loading)
    LinearLayout loading;

    // 所以参数的字符串：wid+channel+frontNotifyUrl+token

    private String wid = null;
    private String key_md5;

    String money_pay;
    private String tokenText;

    private String channel = null;

    private static final String MY_MONEY = "MONEY";
    private static final String MY_WID = "WID";


    @Override
    public int bindLayout() {
        return R.layout.activity_money;
    }

    @Override
    public void initToolbarColor() {
        color = getResources().getColor(R.color.actionbar_title_bg);
        statusBarAlpha = 60;
    }

    private TextView[] textViews;

    @Override
    public void initView(View view) {

        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        textViews = new TextView[]{ten, fifty, oneBai, wubai, other};
        moneyEd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                money_pay = s.toString();
            }
        });
    }


    @Override
    public void doBusiness(Context mContext) {
        tokenText = getIntent().getStringExtra("token");
        String result = getIntent().getStringExtra("myMoney");
        ten.setSelected(true);
        wxPay.setSelected(true);
        myMoney.setText(result + "");
        channel = "9";
        money_pay = "10";
        loading.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    @Override
    public void resume() {
        initUser();

    }

    private void initUser() {
        JSONObject jsonWp_token = new JSONObject();
        try {
            jsonWp_token.put("token", tokenText);
            OkHttpUtils.get()
                    .url(WP_USER_BALANCES)
                    .addParams("p", jsonWp_token.toString())
                    .build()
                    .execute(new UserMoney(MY_MONEY));
            OkHttpUtils.get()
                    .url(WP_USER_CUSTOMER)
                    .addParams("p", jsonWp_token.toString())
                    .build()
                    .execute(new UserMoney(MY_WID));
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    private class UserMoney extends StringCallback {

        private String type;

        public UserMoney(String type) {
            this.type = type;
        }

        @Override
        public void onError(Call call, Exception e, int id) {

        }

        @Override
        public void onResponse(String response, int id) {
//            Log.e("UserMoney", response);

            try {
                JSONObject resultS = new JSONObject(response);
                String code = resultS.getString("code");
                if (code.equals("200")) {
                    if (type.equals(MY_MONEY)) {
                        double result = resultS.getDouble("result");
                        myMoney.setText(result + "");
                    } else if (type.equals(MY_WID)) {
                        JSONObject result = resultS.getJSONObject("result");
                        wid = result.getString("wid");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void destroy() {

    }

    public void isSelect(int id) {
        for (TextView textView : textViews) {
            textView.setSelected(false);
            if (textView.getId() == id) {
                textView.setSelected(true);
                if (textView.getText().toString().equals("其他金额")) {
                    moneyEd.setVisibility(View.VISIBLE);
                    money_pay = null;
                } else {
                    money_pay = textView.getText().toString();
                    moneyEd.setVisibility(View.GONE);
                }
            }
        }
    }


    @OnClick({R.id.wx_pay, R.id.zfb_pay, R.id.pay, R.id.one_bai, R.id.ten, R.id.fifty, R.id.wubai, R.id.other})
    public void onClick(View view) {


        switch (view.getId()) {

            case R.id.wx_pay:
                if (wxPay.isSelected()) {
                    break;
                }

                wxPay.setSelected(true);
                zfbPay.setSelected(false);
                channel = "9";
                break;
            case R.id.zfb_pay:
                if (zfbPay.isSelected()) {
                    break;
                }
                wxPay.setSelected(false);
                zfbPay.setSelected(true);
                channel = "其他";
                break;

            case R.id.ten:
                isSelect(view.getId());
                break;
            case R.id.one_bai:
                isSelect(view.getId());
                break;
            case R.id.fifty:
                isSelect(view.getId());
                break;
            case R.id.wubai:
                isSelect(view.getId());
                break;
            case R.id.other:
                isSelect(view.getId());
                break;
            case R.id.pay:
                if (money_pay != null) {
                    loading.setVisibility(View.VISIBLE);
                    initPay();
                } else {
                    if (moneyEd.getText().toString() != null) {
                        loading.setVisibility(View.VISIBLE);
                        initPay();
                    } else {
                        SnackbarUtil.shortMake(pay, "请输入金额").show();
                    }
                }

                break;
        }


    }

    private void initPay() {
        String key = wid + channel + "123.com" + tokenText;
        try {
            key_md5 = md5(key);
            JSONObject typeJson = new JSONObject();
            typeJson.put("wid", wid);
            typeJson.put("money", money_pay);
            typeJson.put("channel", channel);
            typeJson.put("frontNotifyUrl", "123.com");
            typeJson.put("key", key_md5);
            typeJson.put("token", tokenText);
            typeJson.put("notifyUrl", "http://weipan.izhipeng.com/weixinPayCallBack.jspa");

            OkHttpUtils.get()
                    .url(WPUrlBase.WP_WX_PAY)
                    .addParams("p", typeJson.toString())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            loading.setVisibility(View.GONE);
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                String code = jsonObject.getString("code");
                                if (code.equals("200")) {
                                    String result = jsonObject.getString("result");
                                    loading.setVisibility(View.GONE);
                                    // 如下方案可在非微信内部WebView的H5页面中调出微信支付
                                    if (result.startsWith("weixin://wap/pay?")) {
                                        Intent intent = new Intent();
                                        intent.setAction(Intent.ACTION_VIEW);
                                        intent.setData(Uri.parse(result));
                                        startActivity(intent);
                                    }
                                } else if (code.equals("500")) {
                                    String msg = jsonObject.getString("msg");
                                    SnackbarUtil.shortMake(pay, msg + "请稍后再试").show();
                                    loading.setVisibility(View.GONE);
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (ActivityNotFoundException ex) {
                                SnackbarUtil.shortMake(pay, "查看是否安装微信客户端").show();
                            }

                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * MD5方法
     *
     * @param text 明文
     * @return 密文
     * @throws Exception
     */
    public static String md5(String text) throws Exception {

        byte[] bytes = text.getBytes("UTF-8");

        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        messageDigest.update(bytes);
        bytes = messageDigest.digest();

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            if ((bytes[i] & 0xff) < 0x10) {
                sb.append("0");
            }

            sb.append(Long.toString(bytes[i] & 0xff, 16));
        }

        return sb.toString().toLowerCase();
    }


}
